<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Switch,
  Textarea,
} from 'ant-design-vue';

import {
  createCapabilityDefinition,
  updateCapabilityDefinition,
} from '#/api/resource-center';

// 类型定义
interface Parameter {
  name: string;
  type: string;
  required: boolean;
  defaultValue: string;
  description: string;
}

interface ReturnValue {
  name: string;
  type: string;
  description: string;
}

interface Constraint {
  type: string;
  condition: string;
  message: string;
}

// Props
const props = defineProps<{
  capability?: any;
  visible: boolean;
}>();

// Emits
const emit = defineEmits<{
  success: [];
  'update:visible': [value: boolean];
}>();

// 响应式数据
const formRef = ref();
const saving = ref(false);

// 表单数据
const formData = reactive({
  name: '',
  code: '',
  category: '',
  status: 'active',
  version: '1.0.0',
  description: '',
  tags: [] as string[],
  parameters: [] as Parameter[],
  returns: [] as ReturnValue[],
  constraints: [] as Constraint[],
  dependencies: [] as string[],
  documentation: '',
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入能力名称' }],
  code: [{ required: true, message: '请输入能力代码' }],
  category: [{ required: true, message: '请选择分类' }],
  status: [{ required: true, message: '请选择状态' }],
  version: [{ required: true, message: '请输入版本号' }],
  description: [{ required: true, message: '请输入能力描述' }],
};

// 计算属性
const isEdit = computed(() => {
  return !!props.capability;
});

// 监听visible变化
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      initializeForm();
    }
  },
);

// 监听capability变化
watch(
  () => props.capability,
  (capability) => {
    if (capability) {
      loadCapabilityData(capability);
    }
  },
);

// 初始化表单
const initializeForm = () => {
  if (props.capability) {
    loadCapabilityData(props.capability);
  } else {
    resetForm();
  }
};

// 加载能力数据
const loadCapabilityData = (capability: any) => {
  Object.assign(formData, {
    name: capability.name || '',
    code: capability.code || '',
    category: capability.category || '',
    status: capability.status || 'active',
    version: capability.version || '1.0.0',
    description: capability.description || '',
    tags: capability.tags || [],
    parameters: capability.parameters || [],
    returns: capability.returns || [],
    constraints: capability.constraints || [],
    dependencies: capability.dependencies || [],
    documentation: capability.documentation || '',
  });
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    category: '',
    status: 'active',
    version: '1.0.0',
    description: '',
    tags: [],
    parameters: [],
    returns: [],
    constraints: [],
    dependencies: [],
    documentation: '',
  });
};

// 添加参数
const addParameter = () => {
  formData.parameters.push({
    name: '',
    type: 'string',
    required: false,
    defaultValue: '',
    description: '',
  });
};

// 删除参数
const removeParameter = (index: number) => {
  formData.parameters.splice(index, 1);
};

// 添加返回值
const addReturn = () => {
  formData.returns.push({
    name: '',
    type: 'string',
    description: '',
  });
};

// 删除返回值
const removeReturn = (index: number) => {
  formData.returns.splice(index, 1);
};

// 添加约束
const addConstraint = () => {
  formData.constraints.push({
    type: '',
    condition: '',
    message: '',
  });
};

// 删除约束
const removeConstraint = (index: number) => {
  formData.constraints.splice(index, 1);
};

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;

    const data = {
      ...formData,
      id: props.capability?.id,
      idid,
    };

    let result;
    result = await (isEdit.value
      ? updateCapabilityDefinition(props.capability.id, data)
      : createCapabilityDefinition(data));

    if (result.code === 200) {
      message.success('保存成功');
      emit('success');
      handleCancel();
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
};
</script>

<template>
  <Modal
    :visible="visible"
    @update:visible="(val) => emit('update:visible', val)"
    :title="isEdit ? '编辑能力定义' : '新建能力定义'"
    width="900px"
    :footer="null"
    :destroy-on-close="true"
  >
    <div class="capability-editor">
      <Form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
      >
        <!-- 基本信息 -->
        <div class="section">
          <h3>基本信息</h3>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="能力名称" name="name">
                <Input v-model="formData.name" placeholder="请输入能力名称" />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="能力代码" name="code">
                <Input v-model="formData.code" placeholder="请输入能力代码" />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="分类" name="category">
                <Select v-model="formData.category" placeholder="请选择分类">
                  <SelectOption value="business">业务能力</SelectOption>
                  <SelectOption value="communication">通信能力</SelectOption>
                  <SelectOption value="analytics">分析能力</SelectOption>
                  <SelectOption value="security">安全能力</SelectOption>
                </Select>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="状态" name="status">
                <Select v-model="formData.status" placeholder="请选择状态">
                  <SelectOption value="active">启用</SelectOption>
                  <SelectOption value="inactive">禁用</SelectOption>
                  <SelectOption value="deprecated">废弃</SelectOption>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="版本" name="version">
                <Input v-model="formData.version" placeholder="请输入版本号" />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="标签" name="tags">
                <Select
                  v-model="formData.tags"
                  mode="tags"
                  placeholder="请输入标签"
                  :max-tag-count="5"
                />
              </FormItem>
            </Col>
          </Row>
          <FormItem label="描述" name="description">
            <Textarea
              v-model="formData.description"
              placeholder="请输入能力描述"
              :rows="3"
            />
          </FormItem>
        </div>

        <!-- 参数定义 -->
        <div class="section">
          <div class="section-header">
            <h3>参数定义</h3>
            <Button type="primary" size="small" @click="addParameter">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加参数
            </Button>
          </div>
          <div v-if="formData.parameters.length === 0" class="empty-state">
            <p>暂无参数定义，请添加参数</p>
          </div>
          <div v-else class="parameters-list">
            <div
              v-for="(param, index) in formData.parameters"
              :key="index"
              class="parameter-item"
            >
              <div class="parameter-header">
                <span>参数 {{ index + 1 }}</span>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click="removeParameter(index)"
                >
                  <IconifyIcon icon="ant-design:delete-outlined" />
                  删除
                </Button>
              </div>
              <Row :gutter="16">
                <Col :span="8">
                  <FormItem
                    label="参数名"
                    :name="['parameters', index, 'name']"
                    :rules="[{ required: true, message: '请输入参数名' }]"
                  >
                    <Input v-model="param.name" placeholder="参数名" />
                  </FormItem>
                </Col>
                <Col :span="6">
                  <FormItem
                    label="类型"
                    :name="['parameters', index, 'type']"
                    :rules="[{ required: true, message: '请选择类型' }]"
                  >
                    <Select v-model="param.type" placeholder="类型">
                      <SelectOption value="string">字符串</SelectOption>
                      <SelectOption value="number">数字</SelectOption>
                      <SelectOption value="boolean">布尔值</SelectOption>
                      <SelectOption value="object">对象</SelectOption>
                      <SelectOption value="array">数组</SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="4">
                  <FormItem label="必填">
                    <Switch v-model="param.required" />
                  </FormItem>
                </Col>
                <Col :span="6">
                  <FormItem label="默认值">
                    <Input v-model="param.defaultValue" placeholder="默认值" />
                  </FormItem>
                </Col>
              </Row>
              <FormItem label="描述">
                <Input v-model="param.description" placeholder="参数描述" />
              </FormItem>
            </div>
          </div>
        </div>

        <!-- 返回值定义 -->
        <div class="section">
          <div class="section-header">
            <h3>返回值定义</h3>
            <Button type="primary" size="small" @click="addReturn">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加返回值
            </Button>
          </div>
          <div v-if="formData.returns.length === 0" class="empty-state">
            <p>暂无返回值定义，请添加返回值</p>
          </div>
          <div v-else class="returns-list">
            <div
              v-for="(ret, index) in formData.returns"
              :key="index"
              class="return-item"
            >
              <div class="return-header">
                <span>返回值 {{ index + 1 }}</span>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click="removeReturn(index)"
                >
                  <IconifyIcon icon="ant-design:delete-outlined" />
                  删除
                </Button>
              </div>
              <Row :gutter="16">
                <Col :span="8">
                  <FormItem
                    label="返回值名"
                    :name="['returns', index, 'name']"
                    :rules="[{ required: true, message: '请输入返回值名' }]"
                  >
                    <Input v-model="ret.name" placeholder="返回值名" />
                  </FormItem>
                </Col>
                <Col :span="8">
                  <FormItem
                    label="类型"
                    :name="['returns', index, 'type']"
                    :rules="[{ required: true, message: '请选择类型' }]"
                  >
                    <Select v-model="ret.type" placeholder="类型">
                      <SelectOption value="string">字符串</SelectOption>
                      <SelectOption value="number">数字</SelectOption>
                      <SelectOption value="boolean">布尔值</SelectOption>
                      <SelectOption value="object">对象</SelectOption>
                      <SelectOption value="array">数组</SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="8">
                  <FormItem label="描述">
                    <Input v-model="ret.description" placeholder="返回值描述" />
                  </FormItem>
                </Col>
              </Row>
            </div>
          </div>
        </div>

        <!-- 约束条件 -->
        <div class="section">
          <div class="section-header">
            <h3>约束条件</h3>
            <Button type="primary" size="small" @click="addConstraint">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加约束
            </Button>
          </div>
          <div v-if="formData.constraints.length === 0" class="empty-state">
            <p>暂无约束条件，请添加约束</p>
          </div>
          <div v-else class="constraints-list">
            <div
              v-for="(constraint, index) in formData.constraints"
              :key="index"
              class="constraint-item"
            >
              <div class="constraint-header">
                <span>约束 {{ index + 1 }}</span>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click="removeConstraint(index)"
                >
                  <IconifyIcon icon="ant-design:delete-outlined" />
                  删除
                </Button>
              </div>
              <Row :gutter="16">
                <Col :span="6">
                  <FormItem
                    label="类型"
                    :name="['constraints', index, 'type']"
                    :rules="[{ required: true, message: '请选择类型' }]"
                  >
                    <Select v-model="constraint.type" placeholder="类型">
                      <SelectOption value="resource_status">
                        资源状态
                      </SelectOption>
                      <SelectOption value="permission">权限</SelectOption>
                      <SelectOption value="environment">环境</SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="9">
                  <FormItem
                    label="条件"
                    :name="['constraints', index, 'condition']"
                    :rules="[{ required: true, message: '请输入条件' }]"
                  >
                    <Input
                      v-model="constraint.condition"
                      placeholder="约束条件"
                    />
                  </FormItem>
                </Col>
                <Col :span="9">
                  <FormItem
                    label="消息"
                    :name="['constraints', index, 'message']"
                    :rules="[{ required: true, message: '请输入消息' }]"
                  >
                    <Input
                      v-model="constraint.message"
                      placeholder="错误消息"
                    />
                  </FormItem>
                </Col>
              </Row>
            </div>
          </div>
        </div>

        <!-- 依赖关系 -->
        <div class="section">
          <h3>依赖关系</h3>
          <FormItem label="依赖能力">
            <Select
              v-model="formData.dependencies"
              mode="multiple"
              placeholder="请选择依赖的能力"
              :max-tag-count="3"
            >
              <SelectOption value="booking_capability">预订能力</SelectOption>
              <SelectOption value="payment_capability">支付能力</SelectOption>
              <SelectOption value="notification_capability">
                通知能力
              </SelectOption>
              <SelectOption value="report_capability">报表能力</SelectOption>
            </Select>
          </FormItem>
        </div>

        <!-- 文档 -->
        <div class="section">
          <h3>文档</h3>
          <FormItem label="能力文档">
            <Textarea
              v-model="formData.documentation"
              placeholder="请输入能力文档"
              :rows="6"
            />
          </FormItem>
        </div>
      </Form>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <Button @click="handleCancel">取消</Button>
        <Button type="primary" @click="handleSave" :loading="saving">
          保存
        </Button>
      </div>
    </div>
  </Modal>
</template>

<style lang="less" scoped>
.capability-editor {
  .section {
    margin-bottom: 24px;
    padding-bottom: 24px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    h3 {
      margin-bottom: 16px;
      color: #262626;
      font-size: 16px;
      font-weight: 500;
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin-bottom: 0;
      }
    }

    .empty-state {
      text-align: center;
      padding: 20px;
      color: #8c8c8c;
      background-color: #fafafa;
      border-radius: 4px;
    }

    .parameters-list,
    .returns-list,
    .constraints-list {
      .parameter-item,
      .return-item,
      .constraint-item {
        margin-bottom: 16px;
        padding: 16px;
        border: 1px solid #f0f0f0;
        border-radius: 6px;
        background-color: #fafafa;

        .parameter-header,
        .return-header,
        .constraint-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          padding-bottom: 8px;
          border-bottom: 1px solid #e8e8e8;
          font-weight: 500;
          color: #262626;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
  }
}
</style>
